import React, { Fragment, useState } from 'react';
import Cls from 'classnames';
import { Form, Collapse, Divider, Row, Col } from 'antd';

import './style.less';
import componentMap from './ComponentMap';

import { CaretRightOutlined } from '@ant-design/icons';
import pageStyles from '@/common/pageLayout.less';

const { Panel } = Collapse;
const prefixCls = 'collapse-form-';
const CollapseForm: React.FC<CollapseFormAPI.CollapseFormRegister> = ({ register }) => {
  const { form, name, isReadOnly, schemas, activeKey, changeActiveKey, disabled } = register;

  const [, setFormData] = useState({})

  /**
   * @contentRender 生成Form.Item 元素
   * @param item 表单属性
   * @param key 遍历标签时唯一标识
   * @returns Col 标签
   */
  const contentRender = (item: any, key: any) => {
    const {
      field,
      required = false,
      slotRender,
      render,
      label,
      labelBefore,
      span = 24,
      message = `请输入${label}`,
      placeholder = `请输入${label}`,
      component,
    } = item;
    // 根据component获取对应控件
    const Comp = componentMap.get(component);
    // 判断slotRender 是否为函数
    const isSlotRender = slotRender && typeof slotRender == 'function';
    const props = {
      disabled: disabled,
      placeholder,
      ...item,
    };

    /**
     * @FormItem 渲染Form.Item 中子元素内容
     * @render 自定义渲染内容
     * @returns Form.Item
     */
    const FormItem = () => {
      const itemValue = form.getFieldValue(field);
      const recordValue = form.getFieldsValue();

      const customRequired = isReadOnly ? false : required;

      const customLabel = () => {
        return (labelBefore != null ? <><a>{labelBefore}</a> <span className={'read-label'}>{label}</span></> : <>{label}</>)
      }
      return (
        <Fragment>
          {isSlotRender ? (
            slotRender(itemValue, recordValue)
          ) :
            (
              render && typeof render == 'function' ?
                (
                  <Form.Item label={customLabel()} className={customRequired && 'collapse-form-item'} rules={[{ required: customRequired, message: message }]} shouldUpdate={(_, value) => { setFormData(value) }}>
                    {render(itemValue, recordValue)}
                  </Form.Item>
                )
                :
                (
                  <Form.Item name={field} label={customLabel()} rules={[{ required: customRequired, message: message }]} shouldUpdate={(_, value) => { setFormData(value) }}>
                    {isReadOnly ? <span>{itemValue ? itemValue : '--'}</span> : <Comp {...props} />}
                  </Form.Item>
                )
            )
          }
        </Fragment>
      );
    };

    return (
      <Col key={`${key}-${field}`} span={span}>
        {FormItem()}
      </Col>
    );
  };

  /**
   * @panelRender 折叠面板子项配置
   * @returns Panel
   */
  const panelRender = () => {
    return schemas.map((items: any) => {
      const isSlotRender = items?.slotRender && typeof items.slotRender == 'function';
      return (
        <Panel className="formCollapsePanelBox" header={<Divider orientation="left">{items.title}</Divider>} key={items.key}>
          {isSlotRender
            ? items.slotRender()
            : items.children &&
            items.children.length > 0 &&
            items.children.map((item: any) => {
              return contentRender(item, items.key);
            })}
        </Panel>
      );
    });
  };

  return (
    <>
      {schemas?.length > 0 && (
        <div className={Cls(pageStyles['fromView-stylesPage'], `${prefixCls}container`)}>
          <Form form={form} name={name} key={name}>
            <Row>
              <Collapse
                className={Cls(pageStyles['commonCollapse'], `${prefixCls}container-item`, isReadOnly ? `${prefixCls}container-item-read` : '')}
                activeKey={activeKey}
                bordered={false}
                onChange={changeActiveKey}
                expandIcon={({ isActive }) => {
                  return <CaretRightOutlined rotate={isActive ? 90 : 0} />;
                }}
                expandIconPosition="end"
              >
                {panelRender()}
              </Collapse>
            </Row>
          </Form>
        </div>
      )}
    </>
  );
};

export default CollapseForm;
